package cn.zxuqian.services;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class ProductService {

    private final RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    public ProductService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @HystrixCommand(fallbackMethod = "backupProductList")
    public String productList() {
        List<ServiceInstance> instances = this.discoveryClient.getInstances("product-service");
        if(instances != null && instances.size() > 0) {
            return this.restTemplate.getForObject(instances.get(0).getUri() + "/list", String.class);
        }

        return "";
    }

    public String backupProductList() {
        return "夹克，毛衣";
    }


    public String productListLoadBalanced() {
        return this.restTemplate.getForObject("http://product-service/list", String.class);
    }

    public String productListZuul() {
        return this.restTemplate.getForObject("http://zuul-server/product/list", String.class);
    }
}
